const { format } = require('date-fns')
/** 手机号格式验证 */
const phoneRegex = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

/** 手机号加密 */
function encryptPhone(phone) {
  // return phoneNumber?.length === 11
  //   ? phoneNumber?.slice(0, 3) + '****' + phoneNumber?.slice(7)
  //   : phoneNumber
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}
/**
 *
 * @param {*} time
 * @returns 格式化后日期 年-月-日 时：分：秒
 */
const timeFormat = (date) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm')
}

const dateFormat = (date) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm')
}

/**
 *
 * @param {*} day
 * @returns 格式化后日期 年-月-日
 */
const dayFormat = (date) => {
  return format(new Date(date), 'yyyy-MM-dd')
}
const { startOfDay, addDays } = require('date-fns')

const getDateCount = async (model, days) => {
  /**
   * @const {now} 服务器当前时间
   * @const {dateNow}  今日 时间  00:00:00 开始
   * @const {dateStart} dateNow - days 开始时间
   * @const {dateEnd} 结束时间 包含当前一天
   * @const {yesterday} 上一天
   * @retuen
   * @const {allDates} 转换全部日期 数组
   * @const {resultMap} 将结果转换为以日期为键 的 字典
   * @const {totalCountn} 总数
   * @const {todayCount} 今日总数
   * @const {yesterdayCount} 昨天总数
   * @return [{ date:"2024-01-01", count:0}]
   *
   */
  const now = new Date()
  const dateNow = startOfDay(now)
  const dateStart = addDays(dateNow, -days)
  const dateEnd = addDays(dateNow, 1)
  const yesterday = addDays(now, -1)

  try {
    // 聚合查询
    const results = await model.aggregate([
      {
        $match: {
          createdAt: {
            $gte: dateStart,
            $lt: dateEnd,
          },
        },
      },
      {
        $group: {
          _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
          count: { $sum: 1 },
        },
      },
      {
        $project: {
          date: '$_id',
          count: 1,
          _id: 0, // 不返回 _id
        },
      },
      {
        $sort: { _id: 1 }, // 按日期排序
      },
    ])

    const allDates = Array.from({ length: days }, (_, i) => {
      const date = addDays(dateStart, i + 1)
      return dayFormat(date)
    })
    //
    const resultMap = results.reduce((acc, { date, count }) => {
      acc[date] = count
      return acc
    }, {})

    // 创建包含所有日期的统计数据
    const finalResults = allDates.map((date) => ({
      date,
      count: resultMap[date] || 0, // 默认值为0
    }))

    const totalCount = finalResults.reduce((total, day) => total + day.count, 0)

    const todayCount =
      finalResults.find((r) => r.date === dayFormat(dateNow))?.count || 0
    const yesterdayCount =
      finalResults.find((r) => r.date === dayFormat(yesterday))?.count || 0

    return {
      totalCount,
      todayCount,
      yesterdayCount,
      finalResults,
    }
  } catch (error) {
    console.error('统计错误:', error)
    return error
  }
}

module.exports = {
  phoneRegex,
  encryptPhone,
  timeFormat,
  dateFormat,
  dayFormat,
  getDateCount,
}
